#include "container.h"

#include "servicecamera.h"
#include "serviceentity.h"
#include "application.h"
#include "servicephysics.h"
#include "collectibleentity.h"


namespace infinity {


Container::~Container()
{
	delete m_slots;
}

bool Container::add(Object& object, int count)
{
	
	//keep a ref on first empty cell
	Slot * ref= NULL;
	Slot * currentSlot = NULL;
	//find same type && id
	for (unsigned int index = 0; index < m_nbSlots; index++)
	{
		currentSlot = m_slots + index;

		if(currentSlot->object.type == object.type && currentSlot->object.id == object.id)
		{
			if(currentSlot->count + count <= SlotCapacity)
			{
				currentSlot->count = currentSlot->count + count;
				return true;
			}
		}

		if(currentSlot->object.type == Object::EMPTY && ref == NULL)
		{
			ref = currentSlot;
		}
	}

	if(ref != NULL)
	{
		ref->object.type = object.type;
		ref->object.id = object.id;
		ref->count = count;

		return true;
	}
	
	return false;

}

bool Container::remove(unsigned int index,int count)
{
	dwAssert(index >= 0 && index < m_nbSlots, "Index Out f bound");
	Slot * currentSlot = m_slots + index;

	if(currentSlot->count > 0)
	{
		currentSlot->count = currentSlot->count-1;

		if(currentSlot->count == 0 )
		{
			currentSlot->count = 0;
			currentSlot->object.type = Object::EMPTY;
			currentSlot->object.id		= 0;
		}
		return true;
	}

	return false;	
}

void Container::dropOne(unsigned int index)
{
	dwAssert(index >= 0 && index < m_nbSlots, "Index Out f bound");
	Slot * currentSlot = m_slots + index;

	if(currentSlot->count > 0)
	{
		ServiceCamera& svcCamera = Application::getInstance().getService< ServiceCamera >();
		dw::graphics::Node* cameraNode = svcCamera.getActiveCameraController()->getMatrix();
		const Vector3f direction(cameraNode->getTransform().at);
		const Vector3f position(cameraNode->getTransform().pos);

		// Spawn entity
		ServiceEntity& serviceEntity = Application::getInstance().getService< ServiceEntity >();

		CollectibleEntity* entity = serviceEntity.spawnEntity< CollectibleEntity >("DestroyedBlock");


		entity->setInitialPosition(position );
		entity->setInitialVelocity(2.0f * direction );
		entity->setTimeToLive(1.0f * 20.0f);
		entity->setObject(currentSlot->object.type, currentSlot->object.id);

		currentSlot->count = currentSlot->count-1;
	}
	if(currentSlot->count == 0 )
	{
		currentSlot->count = 0;
		currentSlot->object.type = Object::EMPTY;
		currentSlot->object.id		= 0;
	}
}

void Container::dropAll(unsigned int index)
{
	dwAssert(index >= 0 && index < m_nbSlots, "Index Out f bound");
	Slot * currentSlot = m_slots + index;

	int count = currentSlot->count;
	for (int nb = 0 ; nb < count; nb++)
	{
		dropOne(index);
	}
}


} // namespace infinity
